// src/api/api.ts
import axios from 'axios'
import type { AxiosInstance, AxiosResponse, AxiosError } from 'axios'
import JSONBig from 'json-bigint'

// 创建 axios 实例
const api: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
  transformResponse: [
    function (data) {
      try {
        return JSONBig({ storeAsString: true }).parse(data)
      } catch (error: unknown) {
        console.error('响应错误:', error)
        return data
      }
    },
  ],
})
// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    // 对响应数据做点什么
    if (response.data && response.data.code && response.data.code !== 0) {
      return Promise.reject(Error(response.data.message))
    }
    return response.data.data
  },
  (error: AxiosError) => {
    // 对响应错误做点什么
    if (error.response?.status === 401) {
      // 处理未授权错误，例如清除token并跳转到登录页
      localStorage.removeItem('userToken')
      window.location.href = '/login'
    }

    console.error('响应错误:', error)
    return Promise.reject(error)
  },
)

export default api
